//msg.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define BUFSZ 512
struct message
{
	long msg_type;
	char msg_text[BUFSZ];
};

int main(void)
{
	int qid;
	key_t key;
	int len;
	stuct message msg;
	
	//根据不同的路径和关键表示产生标准的key
	if((key = ftok(".", 'a')) == -1)
	{
		perror("ftok error");
		exit(1);
	}
	//create msg queue
	if((qid = msgget(key, IPC_CREAT|0666)) == -1)
	{
		perror("msgget error");
		exit(1);
	}
	printf("opened queue %d\n", qid);
	puts("please enter the message to queue:");
	if((fgets((&msg)->msg_text, BUFSZ, stdin)) == NULL)
	{
		puts("no message");
		exit(1);
	}
	msg.msg_type = getpid();
	len = strlen(msg.msg_text);
	
	//add msg to the msg queue
	if((msgsnd(qid, &msg, len, 0)) < 0)
	{
		perror("message posted");
		exit(1);
	}
	//read the msg queue
	if(msgrcv(qid, &msg, BUFSZ, 0, 0) < 0)
	{
		perror("msgrcv error");
		exit(1);
	}
	
	printf("message is :%s\n", (&msg)->msg_text);
	//remove the msg queue from the system kernel
	if((msgctl(qid,IPC_RMID, NULL)) < 0)
	{
		perror("msgctl error");
		exit(1);
	}
	exit(0);
		
}